package com.ksd.quartz.util;

import java.io.*;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;

public class FileDownloader {
    // 列出服务器目录下的所有文件
    private static List<String> listFilesInServerDirectory(String serverUrl) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newBuilder()
                .followRedirects(HttpClient.Redirect.NORMAL) // 自动处理重定向
                .build();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(serverUrl))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() != 200) {
            throw new IOException("Failed to list files, status code: " + response.statusCode());
        }

        String responseBody = response.body();
        List<String> fileNames = new ArrayList<>();
        // 假设服务器返回的是HTML列表，解析出文件名
        // 这里简单示例，实际可能需要更复杂的HTML解析，如使用Jsoup
        int startIndex = 0;
        while ((startIndex = responseBody.indexOf("<a href=\"", startIndex)) != -1) {
            startIndex += 9;
            int endIndex = responseBody.indexOf("\"", startIndex);
            String fileName = responseBody.substring(startIndex, endIndex);
            if (!fileName.equals(".") && !fileName.equals("..")) {
                fileNames.add(fileName);
            }
            startIndex = endIndex;
        }
        return fileNames;
    }

    // 下载单个文件
    private static void downloadFile(String fileUrl, String savePath) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newBuilder()
                .followRedirects(HttpClient.Redirect.NORMAL) // 自动处理重定向
                .build();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(fileUrl))
                .build();

        HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
        if (response.statusCode() != 200) {
            throw new IOException("Failed to download file, status code: " + response.statusCode());
        }

        try (BufferedInputStream in = new BufferedInputStream(response.body());
             FileOutputStream fileOutputStream = new FileOutputStream(savePath)) {
            byte[] dataBuffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
        }
    }

    // 下载服务器目录下所有文件
    public static void downloadAllFiles(String serverDirUrl, String localDirPath) throws IOException, InterruptedException {
        List<String> fileNames = listFilesInServerDirectory(serverDirUrl);
        for (String fileName : fileNames) {
            String fileUrl = serverDirUrl + fileName;
            String savePath = localDirPath + File.separator + fileName;
            File saveDir = new File(savePath).getParentFile();
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }
            downloadFile(fileUrl, savePath);
        }
    }

    public static void main(String[] args) {
//        String serverDirUrl = "http://192.168.10.244:8080/storage/upload/videos/zipFile/playservice_upload_data/20250418161718";
//        String serverDirUrl = "http://192.168.10.244:8080/data/lnmp/www/ksd_cloud/storage/app/public/upload/videos/zipFile/playservice_upload_data/20250418161718";
        String serverDirUrl = "http://192.168.10.244:8080/home/test/wuyun/app/upload/2025/04/18/电影音乐内容数据_20250418161716A001.zip";
        String localDirPath = "D:/playservice/云服务器升级数据/apk_version/";
        try {
            downloadAllFiles(serverDirUrl, localDirPath);
            System.out.println("所有文件下载完成");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}